<?php
/**
 * 物料控制器
 * User: ws
 * Date: 2018/8/6
 * Time: 19:29
 */

namespace app\admin\controller;
use app\admin\model\Materiel as MaterielModel;

class Materiel extends Init
{
    function index()
    {
        if ($this->request->isAjax()) {
            $list = MaterielModel::paginate(200)->toArray();
            return json($result = ['code' => 0, 'msg' => '获取成功', 'data' => $list['data'], 'count' => $list['total']]);
        }
        return view('list');
    }


    function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $model = new MaterielModel();

            if (empty($data['materiel_id'])) {
                unset($data['materiel_id']);
                $rul = $model->add($data);
            } else {
                $rul = $model->edit($data);
            }

            if ($rul) {
                return json(array('code' => 200, 'msg' => '添加成功'));
            }
            return json(array('code' => 0, 'msg' => '添加失败'));
        }


        $parent = MaterielModel::where('parent_id', 0)->paginate(30)->toArray();
        if (!empty(input('id'))) {
            $list = MaterielModel::where('materiel_id', input('id'))->find()->toArray();
            return view('add', ['list' => $list, 'pare' => $parent['data']]);
        }
        $list['code'] = '';
        $list['name'] = '';
        $list['materiel_id'] = '';
        $list['value_z'] = '';
        $list['value_y'] = '';
        $list['value_x'] = '';
        $list['rent'] = '';
        $list['settlement'] = '';
        $list['deposit'] = '';
        $list['one_proportion'] = '';
        $list['two_proportion'] = '';
        return view('add', ['pare' => $parent['data'],'list'=>$list]);
    }


    public function del()
    {
        $id = input('param.id');
        $lalel = MaterielModel::where('parent_id', $id)->find();
        if ($lalel) {
            return json(array('code' => 0, 'msg' => '删除失败，请先删除下级标签'));
        }
        if (!MaterielModel::destroy(['materiel_id' => $id])) {
            return json(array('code' => 0, 'msg' => '删除失败'));
        }
        return json(array('code' => 200, 'msg' => '删除成功'));
    }
}